
package org.example.demo.controller;

//写一个方法

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.example.demo.model.Student;
import org.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("student")
@Api(tags = "学生信息管理系统")
public class StudentController{

    @Autowired
    private StudentRepository stuR;

    @GetMapping
    @ApiOperation(value = "查找学生111",notes="注：可以找到所有学生信息")
    public List<Student> getStudent(){
        return stuR.findAll();
    }

    @PostMapping
    @ApiOperation(value="创建学生111",notes="注：创建学生")
    public Student creatStudent(@ApiParam(name="student",value="学生对象",required=true)
                                    @RequestBody Student student){
        return stuR.save(student);
    }

    @PutMapping("{id}")
    @ApiOperation(value="修改学生111",notes="注:根据id修改学生姓名和年龄")
    public ResponseEntity updateStudent(@ApiParam(name="id")@PathVariable Long id,
                                        @ApiParam(name="student")@RequestBody Student studentDetails){
        Optional<Student> op = stuR.findById(id);
        if(!op.isPresent()){
            return ResponseEntity.notFound().build();
        }
        Student student = op.get();
        //student是通过id获取的数据库的student，我们需要把studentDetails的数据给它
        student.setName(studentDetails.getName());
        student.setAge(studentDetails.getAge());
        Student newStudent = stuR.save(student);
        return ResponseEntity.ok(newStudent);

    }

    @DeleteMapping("{id}")
    @ApiOperation(value="删除学生111",notes="注：根据id删除学生")
    public ResponseEntity deleteStudent(@ApiParam(name="id",value="这是学生id", example="1") @PathVariable Long id){
        if(!stuR.existsById(id)){
            return ResponseEntity.notFound().build();
        }
        stuR.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}